package com.cloud.system.controller;

import cn.hutool.crypto.SecureUtil;
import com.cloud.common.domain.Result;
import com.cloud.controller.BaseController;
import com.cloud.domain.LoginUser;
import com.cloud.entity.SysUser;
import com.cloud.enums.BusinessType;
import com.cloud.common.enums.CheckType;
import com.cloud.logs.Logs;
import com.cloud.user_info.service.ISysUserService;
import com.cloud.utils.SecurityUtils;
import com.cloud.utils.StringUtils;
import com.cloud.utils.SystemUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author yzj
 */
@Tag(name = "个人信息")
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Operation(summary = "查询个人信息")
    @GetMapping("/getInfo")
    public Result getInfo() {
        Map<String, Object> userMap = new HashMap<>();
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        if (StringUtils.isNotNull(sysUser)) {
            userMap.put("sysUser", sysUser);
            userMap.put("roleGroup", userService.selectUserRoleGroup(sysUser.getUserName()));
            userMap.put("postGroup", userService.selectUserPostGroup(sysUser.getUserName()));
        }
        return Result.success("查询成功", userMap);
    }

    @Operation(summary = "修改个人信息")
    @Logs(title = "修改个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public Result update(@RequestBody SysUser user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhone())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkPhoneUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkEmailUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            sysUser.setNickName(user.getNickName());
            sysUser.setPhone(user.getPhone());
            sysUser.setEmail(user.getEmail());
            sysUser.setSex(user.getSex());
            return Result.success("操作成功");
        }
        return Result.error("操作失败，请联系管理员");
    }

    @Operation(summary = "重置密码")
    @Logs(title = "重置个人密码", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUser().getUserName();
        String password = loginUser.getUser().getPassword();
        if (!SystemUtils.matchesPassword(oldPassword, password)) {
            return Result.error("修改密码失败，旧密码错误");
        }
        if (SystemUtils.matchesPassword(newPassword, password)) {
            return Result.error("新密码不能与旧密码相同");
        }
        // 修改账户密码
        int rows = userService.resetUserPwd(userName, SecureUtil.md5(newPassword));
        if (rows > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecureUtil.md5(newPassword));
            return Result.success("操作成功");
        }
        return Result.error("操作失败，请联系管理员");
    }

    @Operation(summary = "修改用户头像")
    @Logs(title = "修改用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public Result avatar(String avatar) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (userService.updateUserAvatar(loginUser.getUser().getUserName(), avatar)) {
            // 更新缓存用户头像
            loginUser.getUser().setAvatar(avatar);
            return Result.success("操作成功", avatar);
        }
        return Result.error("操作失败，请联系管理员");
    }

}
